# -*- coding:utf8 -*-
# __author__ = "zhangying"
# __date__ = "2019/2/21 13:17"
#获取真正的设备信息 调用dos_cmd.py
from util.dos_cmd import DosCmd
from util.port import Port
import threading
from util.write_user_command import WriteUserCommand
import time


class Server:
    def __init__(self):
        self.dos = DosCmd()
        #self,get_devices()获取设备信息--（个数）
        self.device_list = self.get_devices()
        self.write_file = WriteUserCommand()

    def get_devices(self):
        '''
        获取设备信息--（个数）
        :return:
        '''
        devices_list = []
        result_list = self.dos.excute_cmd_result('adb devices')
        if len(result_list)>=2:
            for i in result_list:
                if 'List' in i:
                    continue
                devices_info = i.split('\t')
                if devices_info[1] =='device':
                    devices_list.append(devices_info[0])
            return devices_list
        else:
            None

    def creart_port_list(self,start_port):
        '''
        创建可用端口
        :return:
        '''
        port = Port()
        port_list = []
        port_list = port.create_port_list(start_port,self.device_list)
        return port_list

    def creat_command_list(self,i):
        '''
        拼接端口
        appium -p 4723 -bp 4701 -U 127.0.0.1:21503
        :return:
        '''
        command_list = []
        appium_port_list = self.creart_port_list(4700)
        bootstrap_port_list = self.creart_port_list(4900)
        device_list = self.device_list
        command = "appium -p "+str(appium_port_list[i])+" -bp "+str(bootstrap_port_list[i])+" -U "+device_list[i]
        command_list.append(command)
        self.write_file.write_data(i,device_list[i],str(bootstrap_port_list[i]),str(appium_port_list[i]))
        return command_list

    def start_server(self,i):
        """
        运行命令,多线程
        ['appium -p 4723 -bp 4701 -U 127.0.0.1:21503 --no=reset --session-override']
        :return:
        """
        self.start_list = self.creat_command_list(i)
        self.dos.excute_cmd(self.start_list[0])

    def kill_server(self):
        server_list = self.dos.excute_cmd_result('tasklist |find "node.exe"')
        if len(server_list)>0:
            self.dos.excute_cmd("taskkill -F -PID node.exe")

    def main(self):
        self.kill_server()
        self.write_file.clear_data()
        for i in range(len(self.device_list)):
            appium_start = threading.Thread(target=self.start_server,args=(i,))
            appium_start.start()
        time.sleep(20)


if __name__ == '__main__':
    server = Server()
    server.main()
    # print(server.get_devices())


